package cc.z8g.browser.core.search

import android.net.Uri
import cc.z8g.browser.utils.isInnerUrl
import cc.z8g.browser.utils.sp.UserSp

/**
 * A UI model for the search box.
 */
object SearchBoxModel {

    /** 返回地址栏应该显示的内容  */
    fun getDisplayContent(url: String, title: String?, isLoading: Boolean): String =
        if (url.isInnerUrl()) {
            ""
        } else if (isLoading) {
            url
        } else {
            val settings = UserSp.getInt(UserSp.KEY_BOX_DISPLAY)
            if (settings == UserSp.BOX_DISPLAY_URL) {
                url
            } else if (settings == UserSp.BOX_DISPLAY_TITLE) {
                if (title.isNullOrEmpty()) url else title
            } else { // domain
                getDisplayDomainName(url)
            }
        }


    /** 从 URL 提取域名  */
    private fun getDisplayDomainName(url: String): String {
        if (url.isEmpty()) return ""
        val uri = Uri.parse(url)
        val host = uri.host
        if (host.isNullOrEmpty()) {
            return url
        }
        return if (host.startsWith("www.")) host.substring(4) else host
    }
}
